#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo/"

kata_containers_repo_url="https://gitee.com/hanliyang-kata-coco/kata-containers.git"
kata_containers_repo_branch="3.13.0-hygon-arch-sig"
kata_containers_repo_dir="${kata_coco_top_dir}/kata-containers"

if [ ! -e ${kata_containers_repo_dir} ]; then
  git clone ${kata_containers_repo_url} \
    -b ${kata_containers_repo_branch} \
    ${kata_containers_repo_dir}
fi

# check and install yq if not exist
echo "Check and Install yq"
command yq > /dev/null
if [ $? -ne 0 ]; then
  DEBUG="y" ${kata_containers_repo_dir}/ci/install_yq.sh
  echo 'export PATH=$PATH:$HOME/go/bin/' >> $HOME/.bashrc
  source $HOME/.bashrc
fi

qemu_repo_url="https://gitee.com/anolis/qemu-kvm.git"
qemu_repo_branch="devel-8.2"
qemu_repo_commit="2738f0c0f26db3d4de536b11c16c45dab598e0c5"
qemu_repo_dir="/dev/shm/openanolis-qemu"

packaging_dir="$(realpath ${kata_containers_repo_dir}/tools/packaging)"

if [ ! -e ${qemu_repo_dir} ]; then
  git clone ${qemu_repo_url} \
    -b ${qemu_repo_branch} \
    ${qemu_repo_dir}
fi
pushd ${qemu_repo_dir}
git reset --hard ${qemu_repo_commit}
popd

install_kata_qemu_deps () {
  echo "Install kata qemu dependencies"
  sudo yum install -y python3-pip ninja-build \
    glib2-devel glib2-static \
    libseccomp libseccomp-devel libseccomp-static \
    libcap-ng-devel \
    glibc-devel glibc-static \
    libzstd libzstd-devel libzstd-static \
    zlib zlib-devel zlib-static \
    pcre2-devel pcre2-static

  # AnolisOS 23's yum source does not container liburing-static, libaio-static

  # build liburing
  if [ ! -e ${kata_coco_top_dir}/liburing ]; then
    git clone https://github.com/axboe/liburing.git \
      ${kata_coco_top_dir}/liburing
    pushd ${kata_coco_top_dir}/liburing
    git reset --hard 9cafb728ac75978b9a3bf952580271f8e636ffd8
    popd
  fi
  pushd ${kata_coco_top_dir}/liburing
  ./configure && \
    make -j$(nproc) && \
    sudo make install
  popd # .../liburing

  # build libaio
  if [ ! -e ${kata_coco_top_dir}/libaio ]; then
    git clone https://pagure.io/libaio.git \
      ${kata_coco_top_dir}/libaio
    pushd ${kata_coco_top_dir}/libaio
    git reset --hard b8eadc9f89e8f7ab0338eacda9f98a6caea76883
    popd
  fi
  pushd ${kata_coco_top_dir}/libaio
  make -j$(nproc) && \
    sudo make install
  popd
  export PKG_CONFIG_PATH=/usr/lib/pkgconfig:$PKG_CONFIG_PATH
}

install_kata_qemu_deps

build_install_qemu () {
  echo "Build and Install kata qemu"
  pushd ${qemu_repo_dir}

  source ${kata_containers_repo_dir}/tools/packaging/scripts/lib.sh

  PREFIX="/opt/kata/" "$packaging_dir/scripts/configure-hypervisor.sh" -s kata-qemu > kata.cfg
  eval ./configure "$(cat kata.cfg)"
  make -j $(nproc --ignore=1)
  sudo -E make install

  popd # ${qemu_repo_dir}
}

build_install_qemu
